package com.runfast.waimai.web.controller;

import com.runfast.common.dao.model.RunfastShopper;
import com.runfast.common.service.RunfastCuseraddressService;
import com.runfast.common.service.RunfastDeliverCostService;
import com.runfast.common.service.RunfastShopperService;
import com.runfast.common.utils.GPSUtil;
import com.runfast.common.utils.TokenUtil;
import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import com.runfast.waimai.dao.model.RunfastGoodsSellOutStatus;
import com.runfast.waimai.dao.model.RunfastGoodsSellOutStatusExample;
import com.runfast.waimai.dao.model.RunfastGoodsSellRecord;
import com.runfast.waimai.entity.Cart;
import com.runfast.waimai.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 外卖订单接口
 */
@RestController("userWmOrderController")
@RequestMapping(value = "/api/user/wm/order", headers = "token")
public class OrderController {

    @Autowired
    private RunfastGoodsSellRecordService orderService;


    @Autowired
    private RunfastBusinessService businessService;

    @Autowired
    private RunfastCuseraddressService cuseraddressService;

    @Autowired
    private RunfastActivityService activityService;


    @Autowired
    private RunfastGoodsSellService goodsSellService;

    @Autowired
    private RunfastDeliverCostService deliverCostService;

    @Autowired
    private RunfastFullLessService fullLessService;

    @Autowired
    private RunfastGoodsSellChildrenService orderItemService;

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private RunfastGoodsSellOptionService optionService;

    @Autowired
    private CartService cartService;

    @Autowired
    private RunfastRefundService refundService;

    @Autowired
    private RunfastGoodsSellOutStatusService goodsSellOutStatusService;

    @Autowired
    private RunfastShopperService shopperService;

    /**
     * 获取订单分页列表
     *
     * @param pageable 分页请求参数
     * @return
     */
    @PostMapping("/list")
    public Result<List<RunfastGoodsSellRecord>> list(@PageableDefault Pageable pageable, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);

        return orderService.list(userId, pageable);
    }


    @PostMapping("/detail")
    public Result detail(@RequestParam Integer orderId, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);

        RunfastGoodsSellRecord goodsSellRecord = orderService.selectByPrimaryKey(orderId);
        if (goodsSellRecord == null) return Result.fail(ResultCode.FAIL, "该订单不存在");
        Cart cart = orderService.orderDetail(userId, goodsSellRecord);

        return Result.ok("", cart);
    }

    /**
     * 确认订单
     *
     * @param order 请求参数
     * @return
     */
    @PostMapping(value = "/confirm")
    public Result confirm(@RequestParam Integer businessId, @RequestParam(required = false) String remark, @RequestHeader String token) {

        Integer userId = TokenUtil.getUserId(token);

        return orderService.confirm(businessId, userId, remark);

    }

    /**
     * 取消订单
     *
     * @param orderId 订单Id
     * @return
     */
    @PostMapping("/cancel")
    public Result cancel(@RequestParam Integer orderId, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);
        return orderService.applyCancel(userId, orderId);

    }


    /**
     * 删除订单
     *
     * @param businessId 商户id
     * @param orderId    订单id
     * @param token
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestParam int orderId, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);

        RunfastGoodsSellRecord order = orderService.selectByPrimaryKey(orderId);
        if (order == null) return Result.fail(ResultCode.ORDER_NOT_EXIST);
        Integer status = order.getStatus();
        if (status != null && status == RunfastGoodsSellRecord.Status.completed.getCode()) {
            RunfastGoodsSellRecord goodsSellRecord = new RunfastGoodsSellRecord();
            goodsSellRecord.setId(orderId);
            goodsSellRecord.setUserDel(1);

            orderService.updateByPrimaryKeySelective(goodsSellRecord);
        } else {
            return Result.fail(ResultCode.FAIL, "未完成订单不能删除");
        }


        return Result.ok("");

    }

    /**
     * 再来一单
     *
     * @param orderId
     * @param token
     * @return
     */
    @PostMapping("/recur")
    public Result recur(@RequestParam Integer orderId, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);

        return cartService.recur(userId, orderId);

    }

    /**
     * 获取订单状态列表
     *
     * @param orderId 订单id
     * @param token
     * @return
     */
    @PostMapping("/status")
    public Result status(@RequestParam int orderId, @RequestHeader String token) {


        RunfastGoodsSellOutStatusExample goodsSellOutStatusExample = new RunfastGoodsSellOutStatusExample();
        goodsSellOutStatusExample.or().andGoodsSellRecordIdEqualTo(orderId);
        goodsSellOutStatusExample.setOrderByClause("id desc");
        List<RunfastGoodsSellOutStatus> statusList = goodsSellOutStatusService.selectByExample(goodsSellOutStatusExample);
        return Result.ok("", statusList);

    }


    /**
     * 申请退款
     * @param orderId      订单号
     * @param reason       退款原因
     * @param refundType   退款类型（全额，部分）
     * @param refundAmount 退款金额
     * @return
     */
    /*@PostMapping("applyRefund")
    public Result applyRefund(@RequestParam Integer orderId, @RequestParam(required = false) String reason, @RequestParam RefundType refundType, @RequestParam(required = false) Integer refundAmount) {
        return orderService.applyRefund(orderId, reason, refundType, refundAmount);
    }*/

    /**
     * 根据选择商品申请退款
     *
     * @param orderId
     * @param refundAmount
     * @param reason
     * @return
     */
    @PostMapping("applyRefund")
    public Result applyRefund(@RequestParam Integer orderId, @RequestParam List orderItemId, @RequestParam(required = false) String reason) {
        return orderService.applyRefund(orderId, orderItemId, reason);
    }


    @PostMapping("applyRefundInfo")
    public Result applyRefundInfo(@RequestParam Integer orderId, @RequestParam List orderItemId) {
        return orderService.applyRefundInfo(orderId, orderItemId);
    }


    @PostMapping("/wallletPay")
    public Result wallletPay(@RequestParam Integer orderId, @RequestParam String password) {

        return orderService.walletPay(orderId, password);
    }

    @PostMapping("/driverLocation")
    public Result driverLocation(@RequestParam Integer driverId) {


        RunfastShopper shopper = shopperService.selectByPrimaryKey(driverId);

        if (shopper == null) return Result.fail(ResultCode.FAIL, "不存在该骑手");

        String latitude = shopper.getLatitude();
        String longitude = shopper.getLongitude();
        Double lat = StringUtils.isBlank(latitude) ? 0d : Double.valueOf(latitude);
        Double lng = StringUtils.isBlank(longitude) ? 0d : Double.valueOf(longitude);
        double[] bd09ToGcj02 = GPSUtil.bd09_To_Gcj02(lat, lng);
        shopper.setLatitude(bd09ToGcj02[0] + "");
        shopper.setLongitude(bd09ToGcj02[1] + "");

        return Result.ok("", shopper);
    }


    /**
     * 用户完成订单
     *
     * @param orderId
     * @return
     */
    @PostMapping("/complete")
    public Result complete(@RequestParam Integer orderId) {


        return orderService.complete(orderId);

    }

}
